<?php
class SNSMsg extends Eloquent {

	protected $table = 'sns_msgs';
	
	/**
	 * 备份一条圈子聊天内容
	 * 
	 * @param object $data
	 */
	public static function _storeChat($data) {
		$chat = new SNSMsg();
		$chat->uuid = $data->uuid;
		$chat->type = $data->type;
		$chat->timestamp = $data->timestamp;
		$chat->from = $data->from;
		$chat->msg_id = $data->msg_id;
		$chat->to = $data->to;
		$chat->chat_type = $data->chat_type;
		if (isset($data->payload->ext)) {
			if (isset($data->payload->ext->associate_id)) {
				$chat->associate_id = $data->payload->ext->associate_id;
			}
			if (isset($data->payload->ext->realname)) {
				$chat->sender_realname = $data->payload->ext->realname;
			}
			if (isset($data->payload->ext->avatar)) {
				$chat->sender_avatar = $data->payload->ext->avatar;
			}
		}
		$msgs = $data->payload->bodies;
		$chat->type = $msgs[0]->type;
		if($chat->type == 'txt'){
			$chat->content = $msgs[0]->msg;
		}
		$chat->created_at = date('Y-m-d H:i:s',substr($data->timestamp, 0, 10));    //环信中的timestamp为13位，与我们的数据库（10位）不一致
		$chat->save();
	}

	public static function getLatestTimestamp()
	{
		$chat = SNSMsg::orderBy('timestamp', 'DESC')->first();
		if ($chat) {
			return $chat->timestamp;
		} else {
			return 0;
		}
	}
}